let logger = require("pomelo-logger").getLogger(__filename);
let gameRecordLoader = require("../entities/gameRecord").loadFromDocument;
let gameRecordCreator = require("../entities/gameRecord").create;
let DateUtil = require("../../utils/dateUtil");

let GameRecordService = function (app) {
    this.app = app;
};

GameRecordService.prototype.getGameRecords = function (msg, player, callback) {
    let gameRecordDao = this.app.get("gameRecordDao");
    gameRecordDao.findByPlayerId(player.getUid(), DateUtil.nowMS() - 7 * 24 * 3600 * 1000, function (documents) {
        var gameRecords = [];
        for (let document of documents) {
            gameRecords.push(gameRecordLoader(document));
        }
        callback(gameRecords);
    });
};

GameRecordService.prototype.addGameRecord = function (gameId, tableId, time, playerScores, callback) {
    let gameRecordDao = this.app.get("gameRecordDao");
    let gameRecord = gameRecordCreator(gameId, tableId, time, playerScores);
    gameRecordDao.addGameRecord(gameRecord.toBSON(), result =>{
        if(!result || result.result.ok != 1) {
            logger.info(`addGameRecord error. result empty`);
            callback(null);
            return;
        }
        callback(gameRecord);
    });
};

GameRecordService.prototype.serializeGameRecords = function (gameRecords) {
    let serializeGameRecords = [];
    for(let gameRecord of gameRecords) {
        serializeGameRecords.push(gameRecord.toJSON());
    }
    return serializeGameRecords;
};

module.exports.create = function (app) {
    return new GameRecordService(app);
};
